# encoding:utf-8

import requests
import base64
import json
import os
def generateAccessToken():
    # 通过百度后台获取apikey和secretkey
    api_key="OnRbUwMMoecp4mmth6SnHxGP"
    secret_key="T9C7IeOkoTlz8U0xGy62YP7j0GdKZLfs"
    client_id=api_key
    client_secret=secret_key
    # 构造请求url
    url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=%s&client_secret=%s"%(client_id,client_secret)
    payload = ""
    headers = {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    }
    # 发起post请求
    response = requests.request("POST", url, headers=headers, data=payload).text
    print(response)
    # 转换json为dict获取accesstoken
    res_dict=json.loads(response)
    access_token=res_dict['access_token']
    # 将token存在本地，每30天更新一次
    with open ('accesstoken.txt','w') as f:
        f.write(access_token)
    f.close()

    return access_token


def getLocalAccessToken():
    # 查看本地是否有token文件
    # 如果没有，调用generateAccessToken()方法获取写入
    if os.path.exists('accesstoken.txt'):
    # 如果有读取并返回
        with open('accesstoken.txt','r') as f:
            data=f.read()
        return data
    else:
        generateAccessToken()
        with open('accesstoken.txt','r') as f:
            data=f.read()
        return data



def getData(img_path):
    '''
    通用文字识别（高精度版）
    '''
    # 构造url
    request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic"
    # 二进制方式打开图片文件
    f = open(img_path, 'rb')
    img = base64.b64encode(f.read())
    # 获取每30天写入本地的accesstoken
    access_token=getLocalAccessToken()
    # 构造请求参数
    params = {"image":img}
    request_url = request_url + "?access_token=" + access_token
    headers = {'content-type': 'application/x-www-form-urlencoded'}
    # 发起请求
    response = requests.post(request_url, data=params, headers=headers)
    if response:
        print (response.json())
        return response.json()